﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;

namespace Hibiku.IO
{
    public class EntityFileReaderWriter<T> where T : class
    {
        private readonly DataContractSerializer m_serializer;

        private readonly string m_directory;
        private readonly string m_fileName;

        public string FilePath
        {
            get { return Path.Combine(m_directory, m_fileName); }
        }


        public EntityFileReaderWriter()
        {
            var applicationDataDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

            m_directory = Path.Combine(applicationDataDir, "Hibiku");
            m_fileName = typeof(T).Name + ".xml";

            m_serializer = new DataContractSerializer(typeof(T));
        }

        public T Read()
        {
            if (!File.Exists(FilePath))
            {
                return null;
            }
            else
            {
                using (var stream = new FileStream(FilePath, FileMode.Open))
                {
                    using (var reader = XmlReader.Create(stream))
                    {
                        var obj = m_serializer.ReadObject(reader);

                        return (T)obj;
                    }
                }
            }
        }

        public void Write(T configuration)
        {
            CreateDirectoryUnlessExists();

            using (var stream = new FileStream(FilePath, FileMode.Create))
            {
                using (var writer = XmlWriter.Create(stream, new XmlWriterSettings() { Indent = true }))
                {
                    m_serializer.WriteObject(writer, configuration);
                }
            }
        }

        private void CreateDirectoryUnlessExists()
        {
            if (!Directory.Exists(m_directory))
            {
                Directory.CreateDirectory(m_directory);
            }
        }
    }
}
